package com.example.smartg;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import okhttp3.Call;
import okhttp3.Response;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.smartg.utils.LogoutDialogUtil;
import com.example.smartg.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class GemanageActivity extends AppCompatActivity {

    public Dialog dialog;
    private ListView lv;
    private int queryFlag = 0;
    public List<Order> historyOrders = new ArrayList<>();
    // 串口配置
    public SerialHelper serialHelper;
    public String SPORT_NAME = "/dev/ttyS4"; //串口路径
    // public static String SPORT_NAME = "/dev/ttyUSB2"; //串口路径
    public int BAUD_RATE = 19200; //波特率
    private String lattice_id = "";

    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("gemanage","onPause");
        closeSerialHelper();
        stopTimer();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.onPause();
        setContentView(R.layout.activity_gemanage);
        // #start 管理员登出通用模块
        TextView textViewUsername = (TextView) findViewById(R.id.user_name);
        String user_name = SpUtils.getString(this, "user_name", "未登录");
        textViewUsername.setText(user_name);
        textViewUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogoutDialogUtil.logout(GemanageActivity.this);
            }
        });
        ImageView home_logo = (ImageView) findViewById(R.id.home_logo);
        home_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeSerialHelper();
                Intent intent = new Intent(GemanageActivity.this, SmartGMainActivity.class);
                startActivity(intent);
            }
        });
        // #end 管理员登出通用模块
        query_color();
        // 初始化串口
        initSerialConfig();
        openSerialHelper();
        // 创建 dialog
        create_dialog(this);
        //加上计时器
        startTimer();
    }


    // 记录上一次操作时间
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        return super.dispatchTouchEvent(ev);
    }

    public void initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率
        serialHelper = new SerialHelper(SPORT_NAME, BAUD_RATE) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                Message message = mHandler.obtainMessage();
                message.obj = paramComBean;
                mHandler.sendMessage(message);
            }
        };
        Log.e("Gemanage","initSerialConfig");
        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
            @Override
            public byte[] execute(InputStream is) {
                try {
                    int available = is.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = is.read(buffer);
                        if (size > 0) {
                            return buffer;
                        }
                    } else {
                        SystemClock.sleep(50);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    public void send_feedback_to_server(String feedback) {
        if (feedback.startsWith("8A")) {
            //开门成功
            if (feedback.length() == 20) {
                if (feedback.substring(16, 18).equals("00")) {
                    switch_feedback("YS001", feedback);
                } else {
                    ToastUtil.error(GemanageActivity.this, "开门失败");
                }
            } else if (feedback.length() == 10) {
                if (feedback.substring(6, 8).equals("00")) {
                    switch_feedback("YS001", feedback);
                } else {
                    ToastUtil.error(GemanageActivity.this, "开门失败");
                }
            }
        }
    }


    //接收到的数据
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            //获取数据
            String str = ByteUtil.ByteArrToHex(comBean.bRec);
            System.out.println(str);
            // 把电磁锁反馈返回服务器
//            send_feedback_to_server(str);
            // 根据反馈弹出提示框
            return false;
        }
    });

    //打开串口（先配置，再打开串口）
    public boolean openSerialHelper() {
        //已经打开串口了就不用再打开
        if (serialHelper.isOpen()) {
            Log.e("串口状态", "已经打开");
            return false;
        }
        //打开串口
        try {
            serialHelper.open();
            Log.e("串口状态", "打开");
        } catch (IOException e) {
            Log.e("串口状态", "关闭");
            e.printStackTrace();
        }

        return true;
    }

    //关闭串口（注销时候或手动关闭）
    public boolean closeSerialHelper() {
        if (!serialHelper.isOpen()) return false;
        serialHelper.close();
        Log.e("Gemanage","serialHelper.close()");
        return true;
    }

    private void open(String cmd_hex) {
        serialHelper.sendHex(cmd_hex); //十六进制数
    }

    //创建可视化柜子
    public void create_cab(JSONArray data) {
        if (data != null) {
            int length = data.length();
            LinearLayout ge_content = (LinearLayout) findViewById(R.id.ge_content);
            ge_content.removeAllViews();
            LinearLayout layout = null;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.MATCH_PARENT);

            for (int i = 0; i < length; i++) {
                int row = i % 6;
                if (row == 0) {
                    if (layout != null) {
                        ge_content.addView(layout);
                    }
                    layout = new LinearLayout(this);
                    layout.setOrientation(LinearLayout.VERTICAL);
                    layout.setLayoutParams(params);
                }
                JSONObject box = data.optJSONObject(i);
                String name = box.optString("box_no");
                String color = box.optString("color");
                TextView textView = new TextView(this);
                textView.setGravity(Gravity.CENTER);
                textView.setText(name);
                LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 50);
                params2.leftMargin = 2;
                params2.rightMargin = 2;
                params2.topMargin = 2;
                params2.bottomMargin = 2;
                textView.setLayoutParams(params2);
                // 设置颜色
                if (color.equals("红色")) {
                    textView.setBackground(getDrawable(R.drawable.btn_red));
                } else if (color.equals("黄色")) {
                    textView.setBackground(getDrawable(R.drawable.btn_yellow));
                } else if (color.equals("绿色")) {
                    textView.setBackground(getDrawable(R.drawable.btn_green));
                } else if (color.equals("白色")) {
                    textView.setBackground(getDrawable(R.drawable.btn_white));
                }
                textView.setTextSize(30);
                textView.setTextColor(Color.BLACK);
                Context context = this;
                if (color.equals("white")) {
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ToastUtil.success(context, "无需清空!");
                        }
                    });
                } else {
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            query_box_info(name);
                        }
                    });
                }
                layout.addView(textView);
            }
            if (layout != null) {
                ge_content.addView(layout);
            }
        }
    }

    //弹出格口详情
    public void showTheDialog(Context context, List<Order> historyOrders, String unpacking_command) {
        dialog.show();
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.choose_ge_dialog_history, null);
        LvAdapterHistory lvAdapter = new LvAdapterHistory(this, historyOrders);
        lv = (ListView) v.findViewById(R.id.history_order);
        lv.setAdapter(lvAdapter);
        Button btn_append = (Button) v.findViewById(R.id.append);
        btn_append.setText("清空");
        btn_append.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清空
                dialog.dismiss();
                create_dialog(GemanageActivity.this);
                open(unpacking_command);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.success(GemanageActivity.this, "开门成功！");
                    }
                });
                switch_feedback("YS001", unpacking_command);
            }
        });
        Button btn_new = (Button) v.findViewById(R.id.create);
        btn_new.setText("取消");
        btn_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 让用户选择新格口的类型
                /// 取消
                dialog.dismiss();
                create_dialog(GemanageActivity.this);
            }
        });
        Window window = dialog.getWindow();
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        window.setLayout(width, height);
        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
    }


    public void create_dialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.custrom_dialog);
        dialog = builder.create();
    }

    // 开门反馈（说明清空成功）
    public void switch_feedback(String cabinet_id, String unpacking_command) {
        String url = "http://10.2.47.115/smartg_api/pickup_manage/clean_feedback";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("cabinet_id", cabinet_id);
            json.put("unpacking_command", unpacking_command);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.e("exception", e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(GemanageActivity.this, "服务器异常-1");
                    }
                });
                query_color();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.success(GemanageActivity.this, "清空成功！");
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.error(GemanageActivity.this, msg);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                query_color();
            }
        });
    }

    // 查询格口详细内容
    public void query_box_info(String box_no) {
        Log.e("box_no", box_no);
        if (queryFlag == 0) {
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/pickup_manage/query_box_no";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("cabinet_id", "YS001");
                json.put("box_no", box_no);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        if (code == 20000) {
                            // Log.e("接收sucess", msg);
                            // 记录首次扫描的条码
                            JSONObject data = jsonObject.optJSONObject("data");
                            Log.e("data", data.toString());
                            JSONArray box_info = data.optJSONArray("box_info");
                            if (box_info == null) {
                                Log.e("box_info", "null");
                            }
                            String unpacking_command = data.optString("unpacking_command");
                            if (unpacking_command.equals("") || box_info == null) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Log.e("XXX","xxxfds");
                                        ToastUtil.error(GemanageActivity.this, box_no + "无需清空！");
                                    }
                                });
                            } else {
                                int len = historyOrders.size();
                                for (int i = 0; i < len; i++) {
                                    historyOrders.remove(0);
                                }
                                Log.e("box_info", box_info.toString());
                                for (int i = 0; i < box_info.length(); i++) {
                                    JSONObject item = box_info.optJSONObject(i);
                                    Order order = new Order();
                                    order.index = Integer.toString(i + 1);
                                    order.batch_num = item.optString("batch_num");
                                    order.material_num = item.optString("material_code");
                                    order.material_quantity = Integer.toString(item.optInt("applicant_num"));
                                    historyOrders.add(order);
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 打开有历史记录的对话框
                                        showTheDialog(GemanageActivity.this, historyOrders, unpacking_command);
                                    }
                                });
                            }

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.error(GemanageActivity.this, msg);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            ToastUtil.error(this, "查询中,请稍等...");
        }
    }
    // 启动的时候或者刷新的时候
    // 查询整个柜子的颜色
    public void query_color() {
        if (queryFlag == 0) {
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/pickup_manage/query_color";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("cabinet_id", "YS001");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        if (code == 20000) {
                            // Log.e("接收sucess", msg);
                            JSONArray data = jsonObject.optJSONArray("data");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    create_cab(data);
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.error(GemanageActivity.this, msg);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            ToastUtil.error(this, "查询中,请稍等...");
        }

    }



    @Override
    protected void onDestroy() {
        closeSerialHelper();
        stopTimer();
        Log.e("gemanage","onDestory");
        super.onDestroy();
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            TextView tv = (TextView) findViewById(R.id.countdown3);
            long mLastActionTime =  SpUtils.getLong(GemanageActivity.this,"lastActionTime",0);
            if((System.currentTimeMillis() - mLastActionTime - 5000) / 1000 > 0){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText( 60 - (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "秒后退出！！");
                    }
                });
            }else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("");
                    }
                });
            }
            Log.e("=1=", (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "");
            if (System.currentTimeMillis() - mLastActionTime - 5000 > 1000 * 60 * 1) {
                stopTimer();
                SpUtils.clear(GemanageActivity.this);
                Intent intent = new Intent(GemanageActivity.this, SmartGMainActivity.class);
                startActivity(intent);
            }
        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");
    }

}